package server

import (
	"github.com/gin-gonic/gin"
	"go.uber.org/zap"
	"strconv"
	"time"
)

type GinServer struct {
	*gin.Engine
	logger *zap.Logger
}

func NewGinServer(mode string, logger *zap.Logger) *GinServer {
	gin.SetMode(mode)

	engine := gin.New()

	// 基础中间件
	engine.Use(
		gin.Recovery(),
		requestLogger(logger),
	)

	return &GinServer{
		Engine: engine,
		logger: logger,
	}
}

func (s *GinServer) Run(port int) error {
	return s.Engine.Run(":" + strconv.Itoa(port))
}

// 自定义请求日志中间件
func requestLogger(logger *zap.Logger) gin.HandlerFunc {
	return func(c *gin.Context) {
		start := time.Now()
		path := c.Request.URL.Path

		c.Next()

		end := time.Now()
		latency := end.Sub(start)

		logger.Info("HTTP Request",
			zap.Int("status", c.Writer.Status()),
			zap.String("method", c.Request.Method),
			zap.String("path", path),
			zap.String("ip", c.ClientIP()),
			zap.Duration("latency", latency),
		)
	}
}
